package cn.tedu.tmall.front.mall.service.impl;

import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.tmall.front.mall.dao.persist.cache.ICartCacheRepository;
import cn.tedu.tmall.front.mall.dao.persist.repository.IGoodRepository;
import cn.tedu.tmall.front.mall.dao.persist.repository.IOrderItemRepository;
import cn.tedu.tmall.front.mall.dao.persist.repository.IOrderRepository;
import cn.tedu.tmall.front.mall.dao.persist.repository.IReceiverAddressRepository;
import cn.tedu.tmall.front.mall.pojo.entity.Order;
import cn.tedu.tmall.front.mall.pojo.entity.OrderItem;
import cn.tedu.tmall.front.mall.pojo.param.OrderAddNewParam;
import cn.tedu.tmall.front.mall.pojo.po.CartPO;
import cn.tedu.tmall.front.mall.pojo.vo.GoodsStandardVO;
import cn.tedu.tmall.front.mall.pojo.vo.OrderListItemVO;
import cn.tedu.tmall.front.mall.pojo.vo.OrderStandardVO;
import cn.tedu.tmall.front.mall.pojo.vo.ReceiverAddressStandardVO;
import cn.tedu.tmall.front.mall.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private IReceiverAddressRepository addressRepository;
    @Autowired
    private IGoodRepository goodRepository;
    @Autowired
    private ICartCacheRepository cartCacheRepository;
    @Autowired
    private IOrderRepository orderRepository;
    @Autowired
    private IOrderItemRepository orderItemRepository;
    @Override
    public void addNew(CurrentPrincipal principal, OrderAddNewParam orderAddNewParam) {
        Long receiverAddressId = orderAddNewParam.getReceiverAddressId();
        ReceiverAddressStandardVO receiverAddressStandardVO = addressRepository.selectById(receiverAddressId);
        if (receiverAddressStandardVO == null) {
            String message = "创建订单失败，收货地址不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        if(!receiverAddressStandardVO.getUserId().equals(principal.getId())){
            String message = "创建订单失败，收货地址不存在";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }
        String fullAddress = receiverAddressStandardVO.getProvince()
                +receiverAddressStandardVO.getCity()
                +receiverAddressStandardVO.getArea()
                +receiverAddressStandardVO.getDetail();
        List<GoodsStandardVO> goodsStandardVOList = new ArrayList<>();
        List<Integer> goodsNums = new ArrayList<>();
        BigDecimal totalPrice = BigDecimal.ZERO;
        Integer totalGoodsNum = 0;
        Long[] goodsIdList = orderAddNewParam.getGoodsIdList();
        for (int i = 0; i < goodsIdList.length; i++) {
            GoodsStandardVO goodsStandardVO = goodRepository.selectById(goodsIdList[i]);
            if (goodsStandardVO == null) {
                String message = "创建订单失败，添加的商品不存在";
                throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
            }
            if(goodsStandardVO.getIsPutOn()!=1){
                String message = "创建订单失败，添加的商品已下架";
                throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
            }
            goodsStandardVOList.add(goodsStandardVO);
            BigDecimal salePrice = goodsStandardVO.getSalePrice();
            CartPO cartPO = cartCacheRepository.getByUserIdAnyGoodsId(principal.getId(), goodsIdList[i]);
            Integer goodsNum = cartPO.getGoodsNum();
            goodsNums.add(goodsNum);
            BigDecimal multiply = salePrice.multiply(new BigDecimal(goodsNum));
            totalPrice = totalPrice.add(multiply);
            totalGoodsNum+=goodsNum;
        }

        Order order = new Order();
        order.setBuyerId(principal.getId());
        order.setBuyerUsername(principal.getUsername());
        order.setOrderNo(UUID.randomUUID().toString());
        order.setReceiverName(receiverAddressStandardVO.getReceiverName());
        order.setReceiverPhone(receiverAddressStandardVO.getReceiverPhone());
        order.setReceiverAddress(fullAddress);
        order.setGoodsNum(totalGoodsNum);
        order.setTotalPrice(totalPrice);
        order.setLogisticsNo("");
        order.setPayChannel(0);
        order.setPayMethod(0);
        order.setOrderState(ORDER_STATE_UNPAID);
        int rows = orderRepository.insert(order);
        if (rows != 1) {
            String message = "创建订单失败失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }

        for (int i = 0; i < goodsStandardVOList.size(); i++) {
            GoodsStandardVO goodsStandardVO = goodsStandardVOList.get(i);
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setGoodsId(goodsStandardVO.getId());
            orderItem.setGoodsCoverUrl(goodsStandardVO.getCoverUrl());
            orderItem.setGoodsTitle(goodsStandardVO.getTitle());
            orderItem.setGoodsNum(goodsNums.get(i));
            orderItem.setSaleUnitPrice(goodsStandardVO.getSalePrice());
            rows = orderItemRepository.insert(orderItem);
            if (rows != 1) {
                String message = "创建订单失败失败，服务器忙，请稍后再尝试！";
                throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
            }
            cartCacheRepository.delete(principal.getId(), goodsStandardVO.getId());
        }

    }

    @Override
    public OrderStandardVO selectByUserByOrderId(CurrentPrincipal principal, Long orderId) {
        OrderStandardVO orderStandardVO = orderRepository.selectByUserByOrderId(principal.getId(), orderId);
        return orderStandardVO;
    }

    @Override
    public List<OrderListItemVO> list(CurrentPrincipal principal) {
        List<OrderListItemVO> list = orderRepository.list(principal.getId());
        return list;
    }
}
